package com.dididoctor.patient.Activity.OneToOneChat.rec;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Utils.LogUtil;

import java.io.File;


/**
 * Created by asus on 2015/5/3.
 */
public class RecorderButton extends Button implements RecordAudio.RecordStateListener {

    private static final int STATE_NORMAL = 1;
    private static final int STATE_RECORDING = 2;
    private static final int STATE_WANT_TO_CANCEL = 3;

    private int mCurState = STATE_NORMAL;
    private int DISTANCE_WANT_TO_CANCEL = 50;
    private boolean isRecording;
    private RecordDialog mDialog;
    private RecordAudio mAudio;
    private boolean isReady;//长按

    public RecorderButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        String dir = ConstantValue.APP_PATH_BASE + "/recorder";
        try {
            File file = new File(dir);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mAudio = RecordAudio.getInstance(dir);

        mAudio.setRecordStataListener(this);

        mDialog = new RecordDialog(context);
        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                LogUtil.info("RecorderButton====的长按事件", ConstantValue.currentStage);
                isReady = true;
                mAudio.prepareAudio();
                return false;
            }
        });

    }

    public interface AudioFinshListener {
        public void onFinish(float seconds, String filePath);
    }

    private AudioFinshListener mListener;

    public void setAudioFinshListener(AudioFinshListener listener) {
        mListener = listener;
    }

    private float mTime;
    private Runnable mGetVoiceLevelRunnable = new Runnable() {
        @Override
        public void run() {
            while (isRecording) {
                try {
                    Thread.sleep(100);
                    mTime += 0.1f;
                    mHandler.sendEmptyMessage(MSG_VOICE_CHANGE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private static final int MSG_PREPARED = 0x100;
    private static final int MSG_VOICE_CHANGE = 0x101;
    private static final int MSG_DISMISS = 0x102;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_PREPARED:
                    LogUtil.info("RecorderButton====显示dialog", ConstantValue.currentStage);
                    isRecording = true;
                    new Thread(mGetVoiceLevelRunnable).start();
                    mDialog.showRecordDialog();
                    break;
                case MSG_VOICE_CHANGE:
                    mDialog.updateVoiceLevel(mAudio.getVoiceLevel(7));
                    break;
                case MSG_DISMISS:
                    LogUtil.info("RecorderButton====消失dialog", ConstantValue.currentStage);
                    mDialog.dismiss();
                    break;
            }
        }
    };

    @Override
    public void wellPrepared() {

        mHandler.sendEmptyMessage(MSG_PREPARED);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        int x = (int) event.getX();
        int y = (int) event.getY();

        try {
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    //isRecording=true;//TODO test
                    changeState(STATE_RECORDING);
                    LogUtil.info("RecorderButton====的按下事件", ConstantValue.currentStage);
                    break;
                case MotionEvent.ACTION_MOVE:

                    if (isRecording) {
                        if (wantToCancel(x, y)) {
                            LogUtil.info("RecorderButton====的移动事件", ConstantValue.currentStage);
                            changeState(STATE_WANT_TO_CANCEL);
                        } else {
                            LogUtil.info("RecorderButton====的移动事件", ConstantValue.currentStage);
                            changeState(STATE_RECORDING);
                        }
                    }
                    LogUtil.info("RecorderButton====的移动事件", ConstantValue.currentStage);
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    if (!isReady) {
                        reset();
                        return super.onTouchEvent(event);
                    }

                    if (!isRecording || mTime < 0.6f) {//prepared 还没有完成
                        LogUtil.info("RecorderButton====时间太短没有完成", ConstantValue.currentStage);
                        mDialog.tooShort();
                        mAudio.cancel();
                        mHandler.sendEmptyMessageDelayed(MSG_DISMISS, 1300);
                    } else if (mCurState == STATE_RECORDING) {
                        LogUtil.info("RecorderButton====录音完成要消失dialog", ConstantValue.currentStage);
                        mAudio.release();
                        mDialog.dismiss();
                        if (mListener != null) {
                            LogUtil.info("RecorderButton====调了onFinish方法" + mListener, ConstantValue.currentStage);
                            mListener.onFinish(mTime, mAudio.getFilePath());
                        }
                    } else if (mCurState == STATE_WANT_TO_CANCEL) {
                        mDialog.dismiss();
                        mAudio.cancel();
                    }
                    reset();
                    LogUtil.info("RecorderButton====的抬起事件", ConstantValue.currentStage);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.onTouchEvent(event);
    }


    private void reset() {
        isRecording = false;
        isReady = false;
        mTime = 0;
        changeState(STATE_NORMAL);
    }

    private boolean wantToCancel(int x, int y) {
        if (x < 0 || x > getWidth()) {
            return true;
        }
        if (y < -DISTANCE_WANT_TO_CANCEL || y > getHeight() + DISTANCE_WANT_TO_CANCEL) {
            return true;
        }
        return false;
    }

    private void changeState(int state) {
        if (mCurState != state) {
            mCurState = state;
            switch (state) {
                case STATE_NORMAL:
                    setText("按住说话");
                    break;
                case STATE_RECORDING:
                    setText("松开结束");
                    LogUtil.info("RecorderButton====松开结束====后面调用手指上滑，取消发送" + mDialog, ConstantValue.currentStage);
                    mDialog.recording();
                    break;
                case STATE_WANT_TO_CANCEL:
                    setText("取消发送");
                    mDialog.wantToCancle();
                    break;
            }
        }
    }


}
